<template>
 <el-dialog 
     :title="nameTitle" 
     :visible.sync="dialogVisible" 
     width="48%" 
     :modal="false"
     :fullscreen="isFullscreen"
     class="drug-info-dialog"
     @close="handleClose"
	 :close-on-click-modal="false"
	 :show-close="false"
     >
     <!-- @contextmenu.native.prevent="showContextMenu" -->
     <!-- 在el-dialog的header部分添加自定义内容 -->
     <template slot="title">
       <div class="dialog-header">
         <span>{{ nameTitle }}</span>
         <div class="header-buttons">
           <el-button 
             type="text" 
             size="medium" 
             @click="toggleFullscreen"
             :icon="isFullscreen ? 'el-icon-minimize' : 'el-icon-full-screen'"
             :title="isFullscreen ? '退出全屏' : '全屏显示'">
           </el-button>
           <el-button 
             type="text" 
             size="medium" 
             @click="dialogVisible = false" 
             icon="el-icon-close"
             title="关闭">
           </el-button>
         </div>
       </div>
     </template>
    <!-- 使用Cascader作为右键菜单 -->
    <el-cascader-panel
      v-if="contextMenuVisible"
      v-model="cascaderValue"
      :options="contextMenuOptions"
      :props="{ expandTrigger: 'hover' }"
      :style="{
        position: 'fixed',
        left: contextMenuX + 'px',
        top: contextMenuY + 'px',
        zIndex: 999,
        border: '1px solid #e0e0e0',
        borderRadius: '4px',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
      }"
      @change="handleMenuSelect"
      @blur="hideContextMenu"
      ref="cascaderMenu">
    </el-cascader-panel>
    <!-- 顶部表单区域 (top) -->
    <div class="form-top">
      <el-form :model="form" ref="topForm" label-width="88px" size="mini" :rules="addRules">
        <!-- 第一行：药品名称 -->
        <el-row :gutter="24">
			<el-col :span="8">
			  <!-- 编码输入框 -->
			<el-form-item label="药品编码" prop="code">
			  <el-input v-model="form.code" @input="handleCodeInput" placeholder="自动生成编码">
			  </el-input>
			</el-form-item>
			</el-col>
          <el-col :span="8">
            <el-form-item label="中药剂型：">
              <el-select v-model="form.dosform" style="margin-left: 4px;" placeholder=''>
                <el-option v-for="item in dosformOptions" :key="item.id" :label="item.label" :value="item.id">
                  <span>{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="中药种类：">
              <el-select v-model="form.tcmType" style="margin-left: 4px;" placeholder=''>
                <el-option v-for="item in tcmTypeOptions" :key="item.id" :label="item.label" :value="item.id">
                  <span>{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 新增的第二行按钮区域 -->
            
        <!-- 第二行：药品剂型、药品类型、抗生素否、皮试否 -->
		<div class="form-top-buttons">
		<!--  <el-button type="primary" size="mini" @click="updateSalePrice" :loading="loading">
		    <i class="el-icon-refresh"></i> 更新售价
		  </el-button> -->
		  <!-- 可以添加其他按钮 -->
		</div>
      </el-form>
    </div>
    
    <!-- 中间标签页区域 (main) -->
    <div class="form-main">
      <el-tabs type="border-card" v-model="activeTab">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本内容[F2]" name="basic">
          <div class="tab-content">
            <basic-info 
              ref="basicInfo"
              :form="form" 
              :form-disabled="formDisabled || mode === 'view'"
              :mode="mode"
              @update="handleFormUpdate">
            </basic-info>
          </div>
        </el-tab-pane>
        
        <!-- 扩展信息标签页 -->
        <el-tab-pane label="扩展信息[F3]" name="extended">
          <div class="tab-content">
            <kz-info 
              ref="kzInfo"
              :form="form" 
              :form-disabled="formDisabled || mode === 'view'"
              :mode="mode"
              @update="handleFormUpdateF3">
            </kz-info>
          </div>
        </el-tab-pane>
        
      </el-tabs>
    </div>
    
    <!-- 底部表格区域 (feet) -->
    <div class="form-feet">
      <div class="CJ">
        <!-- 修改厂家标题按钮区域 -->
        <div class="CJ-title">
          <span class="title-text">厂家信息</span>
          <div class="title-buttons" v-if="mode !== 'view'">
            <el-button type="text" icon="el-icon-plus" @click="addManufacturer"></el-button>
            <el-button type="text" icon="el-icon-edit" @click="editManufacturer" :disabled="!currentManufacturer"></el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteManufacturer" :disabled="!currentManufacturer"></el-button>
          </div>
          <div class="title-buttons" v-else>
            <el-button type="text" icon="el-icon-plus" disabled></el-button>
            <el-button type="text" icon="el-icon-edit" disabled></el-button>
            <el-button type="text" icon="el-icon-delete" disabled></el-button>
          </div>
        </div>
        <div class="CJ-table">
			<!-- height="100%" -->
          <el-table
            :data="manufacturerData"
			highlight-current-row
            border
            style="width: 100%"
            @current-change="handleManufacturerSelect">
            <el-table-column
              type="index"
              label="行号"
              width="50"
              align="center">
            </el-table-column>
			<el-table-column prop="state" label="有效状态" width="120" sortable>
				<template slot-scope="{ row }">
					<span style="color: #00557f;font-weight: bold;">{{ statusMap[row.state] }}</span>
				</template>
			</el-table-column>
            <el-table-column
              prop="manufacturerName"
              label="生产厂家"
              width="180">
            </el-table-column>
            <el-table-column
              prop="expyDate"
              label="有效期天数"
              width="120">
            </el-table-column>
			
            <el-table-column
              prop="orplc"
              label="产地"
              width="120">
            </el-table-column>

            <el-table-column
              prop="manuLotnum"
              label="生产批号"
              width="120">
            </el-table-column>
 
			<el-table-column
			  prop="chsName"
			  label="医保名称"
			  width="120">
			</el-table-column>
			<el-table-column
			  prop="chsCode"
			  label="医保编码"
			  width="100">
			</el-table-column>

          </el-table>
        </div>
      </div>
    </div>
    
    <!-- 修改底部按钮区域 -->
    <div slot="footer" class="dialog-footer" v-if="mode !== 'view'">
      <el-button size="mini" type="primary" @click="submitForm">
        {{ mode === 'add' ? '确定' : '保存' }}
      </el-button>
      <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
    </div>
    <div slot="footer" class="dialog-footer" v-else>
      <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
    </div>
	

    <!-- 厂家信息弹窗 -->
    <el-dialog
      title="厂家信息"
      :visible.sync="manufacturerDialogVisible"
      width="40%"
	  :modal="false"
	  :show-close="false"
      :before-close="handleCloseManufacturerDialog">
	  <!-- 在el-dialog的header部分添加自定义内容 -->
	  <template slot="title">
	    <div class="dialog-header">
	      <span>厂家信息</span>
	      <div class="header-buttons">
	        <el-button 
	          type="text" 
	          size="medium" 
	          @click="manufacturerDialogVisible = false" 
	          icon="el-icon-close"
	          title="关闭">
	        </el-button>
	      </div>
	    </div>
	  </template>
      <el-form :model="manufacturerForm" :rules="prodentrules" ref="manufacturerForm" label-width="120px" size="mini" style="font-size: 12px;">
        <el-row :gutter="20">
          <el-col :span="12">
			<el-form-item label="生产厂家" prop="prodentpId">
			  <!-- selectName -->
			  <el-select 
			    v-model="manufacturerForm.prodentpId" 
			    filterable
			    remote
			    :remote-method="CJsearchNameMethod"
			    @focus="handlefoucsNameCJ" 
			    @change="handleNameChangeCJ" 
			    :popper-append-to-body="false"
			    :loading="loading"
			  >
			  <!-- 选项组 -->
			  <el-group>
			    <!-- 固定头部 -->
			    <div class="select-header" slot="header" 
			    style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-between;padding: 8px;
			    position: sticky;top:0;z-index: 10;background-color: #f1f1f1;">
			      <span style="width: 48px;">厂家序号</span>
			      <span>厂家名称</span>
				  <span>厂家编码</span>
			      <span>生产地</span>
			    </div>
			    <el-option 
			      v-for="item in cjNameOptions" 
			      :key="item._uid" 
			      :label="item.label" 
			      :value="item.id"
			    >
			      <div id="optionItem">
			        <span style="width: 48px;">{{ item.id }}</span>
			        <el-tooltip class="item" effect="light" :content="item.manufacturerName" placement="top">
					  <span style="width: 188px;">{{ item.manufacturerName }}</span>
			        </el-tooltip>
					<span style="width: 48px;">{{ item.coding }}</span>
			        <span>{{ item.origin }}</span>
			      </div>
			    </el-option>
			    </el-group>
			    <!-- 加载状态提示 -->
			    <div v-if="loading" slot="empty" class="load-more">
			      <i class="el-icon-loading"></i> 加载中...
			    </div>
			    <div v-else-if="scrollLoading" slot="empty" class="load-more">
			      <i class="el-icon-loading"></i> 加载更多...
			    </div>
			    <div v-else-if="!hasMore && NameOptions.length > 0" slot="empty" class="load-more">
			      没有更多数据了
			    </div>
			    <div v-else-if="NameOptions.length === 0" slot="empty" class="load-more">
			      暂无数据
			    </div>
			  </el-select>
			</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家编码" prop="coding">
              <el-input v-model="manufacturerForm.coding"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
		<!-- 按照JS文件格式组织的其他表单项 -->
		    <el-row :gutter="20">
		      <!-- 有效天数 -->
		      <el-col :span="12">
		        <el-form-item label="有效天数" prop="expyDate">
		          <el-input v-model="manufacturerForm.expyDate"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 有效状态 -->
		      <el-col :span="12">
		        <el-form-item label="有效状态" prop="state">
		          <el-select v-model="manufacturerForm.state">
		            <el-option 
		              v-for="item in statusOptions" 
		              :key="item.id" 
		              :label="item.label" 
		              :value="item.id"
		            ></el-option>
		          </el-select>
		        </el-form-item>
		      </el-col>
		    </el-row>
		

		      <!-- 集采中选 -->
		      <el-col :span="12">
		        <el-form-item label="集采中选" prop="gatherBuyType">
		          <el-select v-model="manufacturerForm.gatherBuyType">
		            <el-option 
		              v-for="item in YNoptions" 
		              :key="item.value" 
		              :label="item.label" 
		              :value="item.id"
		            ></el-option>
		          </el-select>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 产地 -->
		      <el-col :span="12">
		        <el-form-item label="产地" prop="orplc">
		          <el-input v-model="manufacturerForm.orplc"></el-input>
		        </el-form-item>
		      </el-col>     
		    </el-row>
		
		      
		      <!-- 医保名称 -->
		      <el-col :span="12">
		        <el-form-item label="医保名称" prop="chsName">
		          <el-input v-model="manufacturerForm.chsName"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 医保编码 -->
		      <el-col :span="12">
		        <el-form-item label="医保编码" prop="chsCode">
		          <el-input v-model="manufacturerForm.chsCode"></el-input>
		        </el-form-item>
		      </el-col>
			</el-row>
			
		    <el-row :gutter="20">
				<!-- 批准文号 -->
				<el-col :span="12">
				  <el-form-item label="批准文号" prop="manuLotnum">
				    <el-input v-model="manufacturerForm.manuLotnum"></el-input>
				  </el-form-item>
				</el-col>
		      <!-- 备注 -->
		      <el-col :span="12">
		        <el-form-item label="备注" prop="remark">
		          <el-input v-model="manufacturerForm.remark"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="saveManufacturer">保存</el-button>
        <el-button size="mini" @click="manufacturerDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
  // selfs / js
  import form from './addForm.js' //Form表单
  // 从第二个JS文件中导入字段配置 基本信息
  import BasicInfo from './F2.vue';
  // 从第3个JS文件中导入字段配置 扩展信息
  import kzInfo from './F3.vue';

  import { basicFieldsF2 } from './formFieldsConfigF2.js';
  // 在顶部引入pinyin-pro
  import { pinyin } from 'pinyin-pro';
  // axios
  import { getDInfo,getManufacturer } from "@/api/MedicenCata.js";
  // import { addTraMedici,UpdateTraMedici,getTraMedic } from "@/api/MedicenCata.js"; 
  
  import { addTraMedici,getTraMedic,UpdateTraMedici }  from "@/api/systemCatalogue/traMedici.js";
export default {
  components:{
    BasicInfo,kzInfo,basicFieldsF2,
  },
  props: ['parentMethod'],
  data() {
    return {
	  mode: 'add', // 默认是新增模式
      dialogVisible: false,
      activeTab: 'basic',
      loading: false,
	  nameTitle:'',
      pageNum: 1, //当前页currentPage
      pageSize: 48, //每页展示条数
      totalSize: 10, //总条数
      form: {},
      NameOptions:[],
	  cjNameOptions:[],
      drugCodeOptions: [],
      bzdwOptions:[],
      drugTypeOption:[{id:1,label:'中药'},{id:2,label:'成药'},{id:3,label:'卫材'},{id:4,label:'血液'},{id:5,label:'疫苗'}], // 药品类型
	  dosformOptions:[{ id:1,label:'饮片'},{ id:2,label:'颗粒'}],
	  tcmTypeOptions:[{id:1,label:'植物类药'},{id:2,label:'动物类药'},{id:3,label:'金石矿物类药'}], // 中药种类
	  // 新增控制变量
	  formDisabled: false,
	  manufacturerButtonsDisabled: false,
	  disablePackingQuantity: false, // 控制包装数量是否禁用
	  showFooterButtons: true,
	  tabsDisabled: false,
      manufacturerData: [],

	  // 新增全屏状态
	  isFullscreen: false,
      addRules:{
        name:[{ required:true,message:'此项必填',trigger:'blur' }],
      },
	  statusOptions:[{id:0,label:'禁用'},{id:1,label:'可用'}], 
	  YNoptions:[{id:0,label:'否',value:'否'},{id:1,label:'是',value:'是'}],
      // 新增右键菜单相关数据
      contextMenuVisible: false,
      contextMenuX: 0,
      contextMenuY: 0,
      cascaderValue: [],
      contextMenuOptions: [
              {
                value: 'delete',
                label: '对齐方式',
                children: [
                  {
                    value: 'size-48',
                    label: '左对齐'
                  },
                  {
                    value: 'size-48',
                    label: '居中对齐'
                  },
                  {
                    value: 'size-48',
                    label: '右对齐'
                  },
                  ]
              },
              {
                value: 'batch-delete',
                label: 'Model大小',
                children: [
                  {
                    value: 'size-48',
                    label: '48%'
                  },
                  {
                    value: 'size-58',
                    label: '58%'
                  },
                  {
                    value: 'size-68',
                    label: '68%'
                  },
                  {
                    value: 'size-88',
                    label: '88%'
                  },
                  {
                    value: 'size-100',
                    label: '100%'
                  },
                  ]
              },
              {
                value: 'batch-delete',
                label: '字体大小',
                children: [
                  {
                    value: 'font-increase',
                    label: '10px (小号)'
                  },
                  {
                    value: 'font-reset',
                    label: '12px (默认)'
                  },
                  {
                    value: 'font-decrease',
                    label: '14px (常规)'
                  },
                  {
                    value: 'font-decrease',
                    label: '16px (偏大)'
                  },
                  {
                    value: 'font-decrease',
                    label: '18px (超大)'
                  },
                  {
                    value: 'font-decrease',
                    label: '20px (最大)'
                  },
                  ]
              },
              {
                value: 'settings',
                label: '排列模式',
                children: [
                  {
                    value: 'layout-2',
                    label: '每行2条'
                  },
                  {
                    value: 'layout-3',
                    label: '每行3条（默认）'
                  },
                  {
                    value: 'layout-4',
                    label: '每行4条'
                  }
                ]
              }
              ,{
                value: 'inspect',
                label: '检查网页源码',
              },
            ],
            dialogWidth: '48%',
            fontSize: 12,
            layoutMode: 3,
      // 无限滚动相关
      allSearchResults: [], // 全部搜索结果
      displayedResults: [], // 当前显示结果
      displayBatchSize: 99, // 每批显示数量
      currentDisplayPage: 1, // 当前显示页
      scrollLoading: false, // 加载状态
      hasMore: true, // 是否有更多数据
      scrollDebounce: null, // 防抖计时器

      drugData: {},
      // 厂家相关数据
      manufacturerDialogVisible: false,
      manufacturerForm: {
        "expyDate":'',
        "barCode": "",
        "bidCnt": '',
        "bidLv": '',
        "chsBeginTime": "",
        "chsCode": "",
        "chsEndTime": "",
        "chsName": "",
        "clinicId": '',
        "createId": '',
        "createTime": "",
        "drugCode": "",
        "drugId": '',
		"coding":'',
        "gatherBuyType": '',
        "id": '',
        "localDrugs": '',
        "manuLotnum": "",
        "netCode": "",
        "orplc": "",
        "prodentpId": '',
        "ratio": "",
        "regBrand": "",
        "regModel": "",
        "regSpc": "",
        "remark": "",
        "spcId": "",
        "state": 1,
        "ypId": ""
      },
	  prodentrules:{
		prodentId:[{ required:true,message:'此项必填',trigger:'change' }], 
	  },
	  statusMap: {
	  	0: '禁用',
	  	1: '可用',
	  },
      currentManufacturer: null,
      isEditMode: false,
	  codePrefix: 'JZZY', // 编码前缀
	  codeLength: 8,      // 编码数字部分长度
	  nextCodeNumber: 1,  // 下一个编码数字
	  isAutoGenerateCode: true, // 是否自动生成编码
    }
  },
  mounted() {
    this.getForm();
    // 添加滚动监听
    this.$nextTick(() => {
      const selectDropdown = document.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
      if (selectDropdown) {
        selectDropdown.addEventListener('scroll', this.handleScroll);
      }
    });
    // 初始化CSS变量
    document.documentElement.style.setProperty('--dialog-font-size', `${this.fontSize}px`)
    
    // 添加点击事件监听器，点击其他地方隐藏菜单
    document.addEventListener('click', this.hideContextMenu)
  },
  // 在beforeDestroy中移除监听
  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener('click', this.hideContextMenu)
    const selectDropdown = document.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
    if (selectDropdown) {
      selectDropdown.removeEventListener('scroll', this.handleScroll);
    }
  },
  
  methods: {
    // 挂载或销毁前后重新赋值后端参数
    getForm(){
      // 左侧提交表单
      this.form = form.map(v => {return v })[0]; // Form
	  console.log(this.form,'zho中药表单');
    },
    // 修改openAddModel方法
    openAddModel(param) {
      // 获取父组件中的药品总条数
      const totalCount = this.$root.totalDrugCount || 0;
      
      // 设置下一个编码数字为总条数+1
      this.nextCodeNumber = totalCount + 1;
      
      if (param.operationType === 'add') {
        this.generateAutoCode(); // 自动生成编码
      }
      
      this.dialogVisible = true;
      this.nameTitle = param.label || '新增中药目录';
      this.isShow = param.isShow;
      this.system = param.system;
      this.mode = param.mode || 'add'; // 设置模式
      
      // 每次打开对话框时重置表单
      // this.resetForm();
      
      // 如果是编辑或查看模式，加载数据
      if ((this.mode === 'edit' || this.mode === 'view') && param.id) {
        this.loadEditData(param.id);
      }
    },

	// 生成自增编码
	generateAutoCode() {
	  const numStr = String(this.nextCodeNumber).padStart(this.codeLength, '0');
	  this.form.code = `${this.codePrefix}${numStr}`;
	  this.nextCodeNumber++;
	},
	  // 监听编码输入框变化
	handleCodeInput(val) {
	  if (val) {
		this.isAutoGenerateCode = false;
	  } else {
		this.isAutoGenerateCode = true;
		this.generateAutoCode();
	  }
	},
	// 更新售价方法
	  // async updateSalePrice() {
	  //   if (!this.form.markUpId || this.form.markUpId !== 1) {
	  //     this.$message.warning('当前加成方式不是比例加成，无法更新售价');
	  //     return;
	  //   }
	    
	  //   if (!this.form.markUpRate) {
	  //     this.$message.warning('请先设置加成率');
	  //     return;
	  //   }
	    
	  //   try {
	  //     this.loading = true;
	  //     // 计算新的销售价格 = 成本价 * (1 + 加成率)
	  //     this.form.salePric = (this.form.purcPric * (1 + this.form.markUpRate)).toFixed(2);
	  //     this.$message.success('售价更新成功');
	  //   } catch (error) {
	  //     console.error('更新售价失败:', error);
	  //     this.$message.error('更新售价失败');
	  //   } finally {
	  //     this.loading = false;
	  //   }
	  // },
	// 新增方法：加载编辑数据
	// 在methods部分修改loadEditData方法
	async loadEditData(id) {
	  try {
	    this.loading = true;
	    let res = await getTraMedic({ id: id });
	    
	    if (res.code === 200) {
	      // 先重置表单
	      this.resetForm();
	      // 根据kcId设置包装数量禁用状态
	      this.disablePackingQuantity = res.data.kcId === 1;
	      // 通知F2组件更新包装数量禁用状态
	      if (this.$refs.basicInfo) {
	        this.$refs.basicInfo.disablePackingQuantity = this.disablePackingQuantity;
	      }
	      // 更新表单数据
	      this.form = {
	        ...this.form,
	        ...res.data
	      };
	      
	      // 处理厂家数据
	      if (res.data.list && res.data.list.length > 0) {
	        this.manufacturerData = res.data.list;
	      } else if (res.data.manufacturerData) {
	        this.manufacturerData = res.data.manufacturerData;
	      }
	      
	      // 如果是查看模式，禁用所有表单元素
	      if (this.mode === 'view') {
	        this.formDisabled = true;
	      }
	    }
	  } finally {
	    this.loading = false;
	  }
	},
	// 禁用所有表单元素
	disableAllFormElements() {
	  // 禁用所有表单元素
	  this.formDisabled = true;
	  
	  // 禁用厂家操作按钮
	  this.manufacturerButtonsDisabled = true;
	  
	  // 修改底部按钮，只保留关闭按钮
	  this.showFooterButtons = false;
	  
	  // 禁用标签页切换（如果需要）
	  this.tabsDisabled = true;
	},
	// 更新加成率方法
	updateMarkUpRate() {
	  if (!this.form.costPric) {
	    this.$message.warning('请先填写成本单价');
	    return;
	  }
	  
	  // 调用F2组件的方法重新计算加成率
	  if (this.$refs.basicInfo) {
	    this.$refs.basicInfo.calculateMarkUpRate();
	    this.$message.success('零售单价已更新');
	  } else {
	    this.$message.error('无法更新加成率，请重试');
	  }
	},
    // 修改handleClose方法
    handleClose() {
      // 重置表单
      this.resetForm();
      this.dialogVisible = false;
    },

	// 厂家名称 =. 
	handlefoucsNameCJ(){
      this.cjName();
    },
    // 处理复选框变化修改handleCheckboxChange方法
    handleCheckboxChange(field) {
      if (field === 'antc') {
        // 当抗生素否状态变化时，通知F3组件
        if (this.$refs.kzInfo) {
          this.$refs.kzInfo.setAntcStatus(this.form.antc === 1);
        }
      }
      this.$message.success(`${field} 值已更新为: ${this.form[field]}`);
    },
	
	// 厂家相关
	// 修改cjName方法
	async cjName(isLoadMore = false) {
	  try {
	    if (!isLoadMore) {
	      this.loading = true;
	    } else {
	      this.scrollLoading = true;
	    }
	    
	    const res = await getManufacturer({
			manufacturerName:this.currentQuery,
			pageNum: this.pageNum,
			pageSize: this.pageSize
	    });
	    
	    if (res.code === 200) {
	      const newData = res.data.content.map(v => ({ 
	        label: v.manufacturerName, 
	        ...v,
	        _uid: Math.random().toString(36).substr(2, 9)
	      }));
	      
	      if (this.isSearchMode) {
	        // 搜索模式：保存所有结果
	        this.allSearchResults = newData;
	        
	        // 显示第一批数据
	        this.currentDisplayPage = 1;
	        this.displayedResults = this.allSearchResults.slice(0, this.displayBatchSize);
	        this.cjNameOptions = this.displayedResults;
	        
	        // 更新是否有更多数据
	        this.hasMore = this.displayedResults.length < this.allSearchResults.length;
	      } else {
	        // 普通浏览模式
	        if (isLoadMore) {
	          this.cjNameOptions = [...this.cjNameOptions, ...newData];
	        } else {
	          this.cjNameOptions = newData;
	        }
	        this.hasMore = res.data.content.length >= this.pageSize;
	      }
	    }
	  } catch (error) {
	    console.error('获取药品数据出错:', error);
	  } finally {
	    this.loading = false;
	    this.scrollLoading = false;
	  }
	},
	CJsearchNameMethod: _.debounce(function(query) {
      this.currentQuery = query.trim();
      this.pageNum = 1;
      this.isSearchMode = true;
      
      if (!this.currentQuery) {
        this.isSearchMode = false;
        this.allSearchResults = [];
        this.cjName();
        return;
      }
      
      // 重置状态
      this.allSearchResults = [];
      this.displayedResults = [];
      this.currentDisplayPage = 1;
      this.hasMore = true;
      
      this.cjName();
    }, 500),
    // 显示右键菜单
    showContextMenu(event) {
      this.contextMenuVisible = true
      this.contextMenuX = event.clientX
      this.contextMenuY = event.clientY
      this.cascaderValue = []
      
      this.$nextTick(() => {
        this.$refs.cascaderMenu.$el.focus()
      })
    },
    // 隐藏右键菜单
    hideContextMenu() {
      this.contextMenuVisible = false
    },
    
    // 处理菜单选择
    handleMenuSelect(value) {
      if (!value || value.length === 0) return
      
      const lastValue = value[value.length - 1]
      
      switch(lastValue) {
        case 'delete':
          this.handleDelete()
          break
        case 'batch-delete':
          this.handleBatchDelete()
          break
        case 'size-48':
          this.setDialogWidth('48%')
          break
        case 'size-58':
          this.setDialogWidth('58%')
          break
        case 'size-68':
          this.setDialogWidth('68%')
          break
        case 'size-88':
          this.setDialogWidth('88%')
          break
        case 'size-100':
          this.setDialogWidth('100%')
          break
        case 'font-increase':
          this.increaseFontSize()
          break
        case 'font-decrease':
          this.decreaseFontSize()
          break
        case 'font-reset':
          this.resetFontSize()
          break
        case 'layout-2':
          this.setLayoutMode(2)
          break
        case 'layout-3':
          this.setLayoutMode(3)
          break
        // 检查网页源码
        case 'inspect':
          this.openDevTools()
          break
      }
      
      this.hideContextMenu()
    },

	// 新增切换全屏方法
	toggleFullscreen() {
	  this.isFullscreen = !this.isFullscreen;
	},
	// 厂家选择之后快速填充
	handleNameChangeCJ(val){
	  // 通过id去找到对应的对象
	  let NameResult = this.cjNameOptions.find(name => name.id === val)
	  console.log(NameResult,'去找到对应的厂家对象');
	  this.drugData = NameResult;
	  if(NameResult){
		  // this.manufacturerForm.id = NameResult.id
	    this.manufacturerForm.prodentpId = NameResult.id
	    this.manufacturerForm.manufacturerName = NameResult.manufacturerName
	    this.manufacturerForm.coding = NameResult.coding
	    this.manufacturerForm.orplc = NameResult.origin
	    // 获取拼音简码（首字母第一位）
	    // this.form.pyCode = this.getFirstLetter(NameResult.manufacturerName);
	    // console.log(this.form.pyCode); // 应输出 "Z"
	  }
	},
    // 打开开发者工具
    openDevTools() {
      try {
        // 尝试使用浏览器API打开开发者工具
        if (window.chrome && chrome.devtools) {
          chrome.devtools.inspectedWindow.eval('console.log("开发者工具已打开")')
        } else {
          // 模拟F12按键
          const event = new KeyboardEvent('keydown', {
            key: 'F12',
            code: 'F12',
            keyCode: 123,
            which: 123,
            bubbles: true,
            cancelable: true
          })
          document.dispatchEvent(event)
        }
        this.$message.success('已尝试打开开发者工具')
      } catch (e) {
        this.$message.warning('无法直接打开开发者工具，请手动按F12')
      }
    },
    // 复制药品名称
    copyDrugName() {
      // 检查是否已选择药品
      if (!this.form.name) {
        this.$message.warning('请先选择药典信息');
        return;
      }
      
      // 创建临时textarea元素
      const textarea = document.createElement('textarea');
      textarea.value = this.form.name;
      textarea.style.position = 'fixed';  // 防止页面滚动
      document.body.appendChild(textarea);
      textarea.select();
      
      try {
        // 执行复制命令
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('药品名称已复制到剪贴板');
        } else {
          this.$message.error('复制失败，请手动复制');
        }
      } catch (err) {
        this.$message.error('复制失败: ' + err);
      }
      
      // 移除临时元素
      document.body.removeChild(textarea);
    },
    
    // Others
    // 新增方法：获取字符串的首字母
    getFirstLetter(str) {
      if (!str || typeof str !== 'string') return '';
      
      try {
        // 1. 用正则提取所有汉字（过滤非汉字字符）
        const chineseChars = str.match(/[\u4e00-\u9fa5]/g) || [];
        if (chineseChars.length === 0) return '';
    
        // 2. 对每个汉字获取拼音首字母
        const initials = chineseChars.map(char => {
          const pinyinResult = pinyin(char, {
            toneType: 'none',
            type: 'array',
            multiple: false, // 只取第一个读音
          })[0] || '';
          return pinyinResult.charAt(0).toUpperCase();
        });
    
        // 3. 组合成简码（如"中国" → "ZG"）
        return initials.join('');
      } catch (error) {
        console.error('拼音转换失败:', error);
        return '';
      }
    },
    // 添加滚动处理方法
    handleScroll(event) {
      const { scrollTop, scrollHeight, clientHeight } = event.target;
      const threshold = 50; // 距离底部50px时加载
      
      if (scrollHeight - (scrollTop + clientHeight) < threshold && this.hasMore && !this.scrollLoading) {
        this.loadMoreData();
      }
    },
    handleFormUpdate(updatedData) {
      // 合并子组件更新的数据到表单
      this.form = {
        ...this.form,
        ...updatedData
      };
    },
    handleFormUpdateF3(updatedData) {
      // 合并子组件更新的数据到表单
      this.form = {
        ...this.form,
        ...updatedData
      };
    },



    // 关闭详情弹窗
    handleCloseDetails(done) {
      done();
    },
    
    // 厂家相关方法
    handleManufacturerSelect(currentRow) {
      this.currentManufacturer = currentRow;
    },
    
	// 添加厂家
	addManufacturer() {
	  this.isEditMode = false;
	  this.currentManufacturer = null;
	  this.manufacturerForm = {
	    	"chsBeginTime": "",
			"chsCode": "",
			"chsEndTime": "",
			"chsName": "",
			"clinicId": 0,
			"cntBuy": 0,
			"createId": 0,
			"createTime": "",
			"expyDate": 0,
			"gatherBuyType": 0,
			"id": 0,
			"manuLotnum": "",
			"manufacturerName": "",
			"name": "",
			"orplc": "",
			"prodentpId": 0,
			"remark": "",
			"state": 1,
			"tcmDrugId": 0
	  };
	  this.manufacturerDialogVisible = true;
	},
    
    // 编辑厂家
    editManufacturer() {
      if (!this.currentManufacturer) {
        this.$message.warning('请先选择一条厂家记录');
        return;
      }
      this.isEditMode = true;
      this.manufacturerForm = JSON.parse(JSON.stringify(this.currentManufacturer));
      this.manufacturerDialogVisible = true;
    },
    
    deleteManufacturer() {
      if (!this.currentManufacturer) {
        this.$message.warning('请先选择一条厂家数据');
        return;
      }
      
      this.$confirm('确认删除该厂家信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.manufacturerData.indexOf(this.currentManufacturer);
        if (index !== -1) {
          this.manufacturerData.splice(index, 1);
          this.$message.success('厂家信息已删除');
          this.currentManufacturer = null;
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
	// 保存厂家信息
	saveManufacturer() {
	  this.$refs.manufacturerForm.validate(valid => {
	    if (valid) {
	      // 准备厂家数据
	      const manufacturer = {
			id:this.manufacturerForm.prodentpId,
			prodentpId:this.manufacturerForm.prodentpId,
	        manufacturerName: this.manufacturerForm.manufacturerName,
	        coding: this.manufacturerForm.coding,
	        expyDate: this.manufacturerForm.expyDate,
	        state: this.manufacturerForm.state,
	        ratio: this.manufacturerForm.ratio,
	        bidCnt: this.manufacturerForm.bidCnt,
	        cntBuy: this.manufacturerForm.cntBuy,
	        gatherBuyType: this.manufacturerForm.gatherBuyType,
	        orplc: this.manufacturerForm.orplc,
	        manuLotnum: this.manufacturerForm.manuLotnum,
	        netCode: this.manufacturerForm.netCode,
	        chsName: this.manufacturerForm.chsName,
	        chsCode: this.manufacturerForm.chsCode,
	        ypId: this.manufacturerForm.ypId,
	        regModel: this.manufacturerForm.regModel,
	        regSpc: this.manufacturerForm.regSpc,
	        remark: this.manufacturerForm.remark
	      };
	
	      if (this.isEditMode && this.currentManufacturer) {
	        // 编辑模式 - 更新现有记录
	        const index = this.manufacturerData.findIndex(
	          item => item.id === this.currentManufacturer.id
	        );
	        if (index !== -1) {
	          // 合并新旧数据
	          manufacturer.id = this.currentManufacturer.id;
	          this.$set(this.manufacturerData, index, manufacturer);
	          this.$message.success('厂家信息更新成功');
	        }
	      } else {
	        // 新增模式 - 添加新记录
	        // manufacturer.id = Date.now(); // 生成唯一ID
	        
	        // 检查是否是第一条默认数据（示例数据）
	        if (this.manufacturerData.length === 1 && 
	            this.manufacturerData[0].manufacturerName === '示例宜宾制药厂') {
	          // 替换默认数据
	          this.manufacturerData.splice(0, 1, manufacturer);
	        } else {
	          // 正常添加新数据
	          this.manufacturerData.push(manufacturer);
	        }
	        this.$message.success('厂家信息添加成功');
	      }
	      
	      // 同步到主表单的list字段
	      this.form.list = [...this.manufacturerData];
	      
	      this.manufacturerDialogVisible = false;
	    }
	  });
	},
    
    handleCloseManufacturerDialog(done) {
      this.$confirm('确认关闭厂家信息窗口?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
        this.currentManufacturer = null;
      }).catch(() => {
        this.$message.info('已取消关闭');
      });
    },
    // 修改submitForm方法
    submitForm() {
		console.log(this.form,'提交的表单数据');
      // 首先校验主表单
      this.$refs.topForm.validate(valid => {
        if (!valid) {
          this.$message.error('请填写完整表单信息');
          return false;
        }
        
        // 检查厂家信息是否存在
        if (this.manufacturerData.length === 0 || 
            (this.manufacturerData.length === 1 && 
             this.manufacturerData[0].manufacturerName === '示例宜宾制药厂')) {
          this.$confirm('检测到您当前还未填写厂家信息, 是否前往填写?', '提示:厂家信息为必填项。', {
            confirmButtonText: '去填写',
            cancelButtonText: '关闭提示',
            type: 'warning'
          }).then(() => {
            this.manufacturerDialogVisible = true;
          }).catch(() => {
            this.$message({ type: 'error', message: '厂家信息为必填项！'});
          });
          return;
        }
        
        // 校验所有子组件表单
        this.validateChildForms().then(allValid => {
          if (allValid) {
            if (this.mode === 'add') {
              this.handleSubmitData();
            } else {
              this.editForm();
            }
          } else {
            // this.$message.error('请检查表单中的错误');
          }
        });
      });
    },

	// 新增方法：校验所有子组件表单
	validateChildForms() {
	  return new Promise(resolve => {
	    try {
	      const promises = [];
	      const invalidTabs = [];
	      
	      // 校验基本信息标签页
	      if (this.$refs.basicInfo && this.$refs.basicInfo.$refs.form) {
	        promises.push(new Promise(resolve => {
	          this.$refs.basicInfo.$refs.form.validate(valid => {
	            if (!valid) {
	              invalidTabs.push('basic');
	              console.error('基本信息标签页验证失败');
	            }
	            resolve(valid);
	          });
	        }));
	      } else {
	        console.error('basicInfo ref 或 form ref 未找到');
	      }
	      
	      // 校验扩展信息标签页
	      if (this.$refs.kzInfo && this.$refs.kzInfo.$refs.form) {
	        promises.push(new Promise(resolve => {
	          this.$refs.kzInfo.$refs.form.validate(valid => {
	            if (!valid) {
	              invalidTabs.push('extended');
	              console.error('扩展信息标签页验证失败');
	            }
	            resolve(valid);
	          });
	        }));
	      } else {
	        console.error('kzInfo ref 或 form ref 未找到');
	      }

	      // 等待所有子组件校验完成
	      Promise.all(promises).then(results => {
	        if (invalidTabs.length > 0) {
	          // 切换到第一个有错误的标签页
	          this.activeTab = invalidTabs[0];
	          this.$message.error(`请检查${this.getTabName(invalidTabs[0])}标签页中的错误`);
	        }
	        resolve(results.every(valid => valid));
	      });
	    } catch (error) {
	      console.error('表单验证出错:', error);
	      resolve(false);
	    }
	  });
	},
	
	getTabName(tab) {
	  const tabNames = {
	    basic: '基本信息',
	    extended: '扩展信息',
	    usage: '使用注意'
	  };
	  return tabNames[tab] || tab;
	},
	// submitForm() {
	//   // 首先进行表单验证
	//   this.$refs.topForm.validate(valid => {
	//     if (!valid) {
	//       this.$message.error('请填写完整表单信息');
	//       return false;
	//     }
	    
	//     // 检查厂家信息是否存在
	//     if (this.manufacturerData.length === 0 || 
	//         (this.manufacturerData.length === 1 && 
	//          this.manufacturerData[0].manufacturerName === '示例宜宾制药厂')) {
	//       this.$confirm('检测到您当前还未填写厂家信息, 是否前往填写?', '提示:厂家信息为必填项。', {
	//         confirmButtonText: '去填写',
	//         cancelButtonText: '关闭提示',
	//         type: 'warning'
	//       }).then(() => {
	//         // 聚焦到厂家信息区域
	//         this.manufacturerDialogVisible = true;
	//       }).catch(() => {
	//         this.$message({ type: 'error', message: '厂家信息为必填项！'});
	//       });
	//       return;
	//     }
	    
	//     // 所有验证通过，提交数据
	//     this.handleSubmitData();
	//   });
	// },
	// 新增handleEditSubmit方法
	async handleEditSubmit() {
		console.log(this.form,'pppppppppppppppppppppppppp');
	  try {
	    // 准备提交数据
	    const submitData = {
	      ...this.form,
	      list: this.manufacturerData.filter(item => item.manufacturerName && item.manufacturerName !== '示例宜宾制药厂')
	    };
	    
	    // 调用修改API
	    let res = await UpdateTraMedici(submitData);
	    
	    if (res.code === 200) {
	      this.$message.success('修改药品信息成功');
	      
	      // 关闭对话框
	      this.dialogVisible = false;
	      
	      // 通知父组件刷新数据
	      this.$emit('refresh');
	    } else {
	      this.$message.error(res.message || '修改药品信息失败');
	    }
	  } catch (error) {
	    console.error('提交药品信息出错:', error);
	    this.$message.error('提交药品信息出错');
	  }
	},
	// 修改editForm方法
	async editForm() {
		
	  // 首先进行表单验证
	  this.$refs.topForm.validate(valid => {
	    if (!valid) {
	      this.$message.error('请填写完整表单信息');
	      return false;
	    }
	    
	    // 检查厂家信息
	    if (this.manufacturerData.length === 0 || 
	        (this.manufacturerData.length === 1 && 
	         this.manufacturerData[0].manufacturerName === '示例宜宾制药厂')) {
	      this.$confirm('检测到您当前还未填写厂家信息, 是否前往填写?', '提示:厂家信息为必填项。', {
	        confirmButtonText: '去填写',
	        cancelButtonText: '关闭提示',
	        type: 'warning'
	      }).then(() => {
	        this.manufacturerDialogVisible = true;
	      }).catch(() => {
	        this.$message({ type: 'error', message: '厂家信息为必填项！'});
	      });
	      return;
	    }
	    // 所有验证通过，提交数据
	    this.handleEditSubmit();
	  });
	},

	// 修改handleSubmitData方法，确保提交正确格式的数据
	// 提交数据的实际方法
	async handleSubmitData() {
	  try {
	    // 准备提交数据
	    const submitData = {
	      ...this.form,
	      list: this.manufacturerData.map(item => ({
	        ...item,
	        // 确保所有必要字段都有值
	        state: item.state || 1,
	        ratio: item.ratio || '',
	        bidCnt: item.bidCnt || 0,
	        cntBuy: item.cntBuy || 0,
	        gatherBuyType: item.gatherBuyType || 0
	      }))
	    };
	    
	    console.log('准备提交的数据:', submitData); // 调试用
	    
	    // 调用API
	    let res;
	    if (this.mode === 'add') {
	      res = await addTraMedici(submitData);
	    } else {
	      res = await UpdateTraMedici(submitData);
	    }
	    
	    if (res.code === 200) {
	      this.$message.success(this.mode === 'add' ? '新增药品信息成功' : '修改药品信息成功');
	      this.dialogVisible = false;
	      this.parentMethod(); // 更新父组件驱动
	    } else {
	      this.$message.error(res.message || (this.mode === 'add' ? '新增药品信息失败' : '修改药品信息失败'));
	    }
	  } catch (error) {
	    console.error('提交药品信息出错:', error);
	    this.$message.error('提交药品信息出错');
	  }
	},
	
	// 重置表单方法
	// 在methods部分修改resetForm方法
	resetForm() {
	  // 重置主表单
	  this.$refs.topForm.resetFields();
	  
	  // 重置表单数据为初始值
	  this.form = {
	    ...form.map(v => {return v })[0], // 从addForm.js导入的初始表单数据
	    drugType: 2 // 默认药品类型为中药
	  };
	  
	  // 重置厂家数据
	  this.manufacturerData = [{
	    manufacturerName: '示例宜宾制药厂',
	    coding: 'YB123',
	    insuranceType: '甲类',
	    origin: '宜宾',
	    registrant: '示例公司',
	    approvalNumber: '国药准字Z123456',
	    factory: '宜宾分厂',
	    selfPayRatio: '10%'
	  }];
	  
	  // 重置其他状态
	  this.currentManufacturer = null;
	  this.isEditMode = false;
	  this.formDisabled = false;
	},

  }
}
</script>

<style lang="less" scoped>
	/deep/ .el-dialog__body{
		padding: 10px;
	}
	.dialog-header {
	  display: flex;
	  height: 28px;
	  justify-content: space-between;
	  align-items: center;
	  width: 100%;
	  span{
		  color: #fff;
		  font-size: 12px;
	  }
	  .header-buttons {
	    display: flex;
	    align-items: center;
	    
	    /deep/ .el-button {
	      padding: 0;
	      margin-left: 8px;
	      color: #fff;
	      
	      &:hover {
	        color: #409EFF;
	        background-color: transparent;
	      }
	    }
	  }
	}
	
	/* 调整全屏模式下的样式 */
	.drug-info-dialog {
	  /deep/ &.is-fullscreen {
	    .el-dialog {
	      width: 100% !important;
	      height: 100%;
	      margin: 0 !important;
	      max-height: none;
	    }
	    
	    .el-dialog__body {
	      height: calc(100% - 55px);
	      overflow: auto;
	    }
	  }
	}
.drug-info-dialog {
  font-family: "Microsoft YaHei", sans-serif;
}
/* 自定义Cascader面板样式 */
.el-cascader-panel {
  font-size: 12px;
  background-color: #d6d6d6;
  .el-cascader-menu {
    min-width: 50px;
    .el-cascader-node {
      padding: 8px 16px;
      height: auto;
      line-height: 1.5;
      
      &:hover {
        background-color: #6f6f6f;
      }
      
      &.is-active {
        color: #fff;
        font-weight: bold;
      }
    }
  }
}
.form-top {
  padding: 0px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 4px;

  /deep/ .el-tabs--border-card{
    width: 100%;
  }
  /deep/ .el-input--mini .el-input__inner{
    height: 26px;
  }
  /deep/ .el-form-item__content{
    // margin-left: -8px;
  }
  /deep/ .el-form-item__label{
    font-size: 12px;
    width: 100px;
  }
  .select-header{
    span{
      width: 168px;
      text-align: center;
    }
  }
  #optionItem {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    text-align: left;
    justify-content: space-between;border: 1px solid #a3a3a3;
    span{
      padding-left: 8px;
      border-right: 1px solid #a3a3a3;
      display: inline-block;
      width: 168px;
      font-size: 12px;
      // height: 26px;
      // line-height: 26px;
      white-space: nowrap;      /* 禁止换行 */
      overflow: hidden;         /* 隐藏溢出内容 */
      text-overflow: ellipsis;  /* 溢出显示省略号 */
    }
  }
}

.form-main {
  margin-bottom: 4px;
}

.tab-content {
  // padding: 15px;
  // min-height: 200px;
}

.form-feet {
  /* margin-top: 1px; */
}

.CJ {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  overflow: hidden;
}

.CJ-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background: #00557f;
  color: white;
  font-size: 14px;
}

.title-text {
  font-weight: bold;
  font-size: 12px;
}

.title-buttons .el-button {
  padding: 0px;
  color: white;
}

.CJ-table {
  width: 100%;
}

.el-table {
  width: 100%;
}

.el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: auto;
}

.el-table--scrollable-y .el-table__body-wrapper {
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
  padding: 10px 10px 0;
  border-top: 1px solid #e6e6e6;
  font-size: 12px;
  .el-button{
  
  }
}

/* 调整表单行间距 */
.el-form-item {
  margin-bottom: 4px;
}
#optionItem {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    text-align: left;
    justify-content: space-between;border: 1px solid #a3a3a3;
    span{
      padding-left: 18px;
      border-right: 1px solid #a3a3a3;
      display: inline-block;
      width: 88px;
      font-size: 12px;
      // height: 26px;
      // line-height: 26px;
      white-space: nowrap;      /* 禁止换行 */
      overflow: hidden;         /* 隐藏溢出内容 */
      text-overflow: ellipsis;  /* 溢出显示省略号 */
    }
  }
</style>